package com.example.demo.service.Impl;

import com.example.demo.entity.*;
import com.example.demo.exception.CustomException;
import com.example.demo.mapper.ClassMapper;
import com.example.demo.mapper.EmpMapper;
import com.example.demo.service.ClassService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClassServiceImpl implements ClassService {
    @Autowired
    private ClassMapper classMapper;


    @Override
    public PageBean page(ClassQueryParam param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(),param.getPageSize());
        //2. 调用mapper的列表查询方法
        List<Clazz> classList = classMapper.getPage(param);
        // 3. 状态处理 【如果结束时间大于当前本地时间，就设置已结课】
        classList.forEach( clazz -> {
            if (clazz.getEndDate().isAfter(LocalDate.now())){
                if (clazz.getBeginDate().isAfter(LocalDate.now())){
                    clazz.setStatus("未开班");
                }else{
                    clazz.setStatus("在读");
                }
            }else {
                clazz.setStatus("已结课");
            }
        });
        Page<Clazz> p = (Page) classList;

        //3. 封装PageBean对象并返回
        return new PageBean(p.getTotal(),p.getResult());
    }

    /**
     * 新增班级
     * @param clazz
     */
    @Override
    public void save(Clazz clazz) {
        //1.补全基本参数
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        classMapper.insert(clazz);
    }

    @Override
    public List<Clazz> getAllClazz() {
        return classMapper.getAllClazz();
    }

    @Override
    public Clazz findById(Integer id) {
        return classMapper.getClazzById(id);
    }

    @Override
    public void update(Clazz clazz) {
        //1.补全基本参数
        clazz.setUpdateTime(LocalDateTime.now());
        classMapper.update(clazz);
    }

    @Override
    public void delete(Integer id) {
        //要求如果该班级下关联的有学生，是不允许删除的，并提示错误信息："对不起, 该班级下有学生, 不能直接删除"
        //1.先去学生表查询是否有在该班级的
        List<Student> stu_lists = classMapper.getStudentByClazzId(id);
        if (stu_lists.size() > 0){
            throw new CustomException(Result.error("对不起, 该班级下有学生, 不能直接删除"));
        }else {
            classMapper.deleteById(id);
        }
    }
}
